﻿using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace WpfApp1
{
    public class ServiceHelper
    {
#pragma warning disable
        private static IServiceProvider serviceProvider;
        private static IServiceCollection services;
#pragma warning restore

        /// <summary>
        /// 服务注册
        /// </summary>
        /// <param name="actions"></param>
        public static void RegisterServices(Type[] typeList)
        {
            if (services == null)
                services = new ServiceCollection();
            Assembly executingAssembly = Assembly.GetExecutingAssembly();
#pragma warning disable
            var types = executingAssembly.GetTypes().Where(p => p.FullName.EndsWith("ViewModel"));
#pragma warning restore
            foreach (var type in types)
            {
                services.AddSingleton(type);
            }
            foreach (var type in typeList)
            {
                services.AddSingleton(type);
            }
        }

        /// <summary>
        /// 服务注册
        /// </summary>
        /// <param name="actionList"></param>
        public static void RegisterServices(params Action<IServiceCollection>[] actionList)
        {
            if (services == null)
                services = new ServiceCollection();
            Assembly executingAssembly = Assembly.GetExecutingAssembly();
            var types = executingAssembly.GetTypes().Where(p => p.FullName.EndsWith("ViewModel"));
            foreach (var type in types)
            {
                services.AddSingleton(type);
            }
            foreach (var action in actionList)
            {
                action.Invoke(services);
            }
        }

        /// <summary>
        /// 构建服务
        /// </summary>
        public static void BuildServices()
        {
            if (services == null)
            {
                throw new Exception("服务为注册，请先调用RegisterServices方法");
            }
            serviceProvider = services.BuildServiceProvider();
        }

        /// <summary>
        /// 获得服务实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>()
        {
#pragma warning disable CS8604 // 引用类型参数可能为 null。
            return serviceProvider.GetService<T>();
#pragma warning restore CS8604 // 引用类型参数可能为 null。
        }
    }
}
